/**
 * AuthorityInterceptor.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2013年8月14日
 */
package com.pshare.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.pshare.tool.SessionTool;
import com.pshare.framework.annotation.IdentityAuth;

/**
 * 权限验证拦截器 针对方法和类
 */
public class AuthorityInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = Logger.getLogger(AuthorityInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.debug("AuthorityInterceptor.preHandler...");

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Object bean = handlerMethod.getBean();
//		AccessAuth access = bean.getClass().getAnnotation(AccessAuth.class);
//		AccessAuth methodAccess = handlerMethod.getMethodAnnotation(AccessAuth.class);

		IdentityAuth idClzAuth = bean.getClass().getAnnotation(IdentityAuth.class);
		IdentityAuth idMethodAccess = handlerMethod.getMethodAnnotation(IdentityAuth.class);

		if (idClzAuth == null && idMethodAccess == null) {
			// 没有声明权限,放行
			return true;
		}

		if (!SessionTool.isLogin(request)) {
			response.getWriter().print("SESSION_TIMEOUT");
			response.setStatus(401);
			response.addHeader("sessionstatus", "timeout");
			return false;
		}

		return true;
	}

}
